vec2 fixuv(in vec2 uv) {
vec2 p = 3. * (2. * uv - iResolution.xy) / min(iResolution.x, iResolution.y);
return p;
}


vec3 drawPoint(in vec2 p, in vec2 pos, in float s, in vec3 color, in vec3 col) {

    col = mix(col, color, smoothstep(s, s * 0.9, length(p - pos)));
    return col;
}

vec3 drawGrid(in vec2 p) {
float f = floor(p.x) + floor(p.y);
vec3 col = mix(vec3(0.75), vec3(0.3), smoothstep(0., 1., mod(f, 2.)));
col = mix(col, vec3(1., 0., 0.), smoothstep(abs(p.x), abs(p.x), fwidth(p.x) * 2.));
col = mix(col, vec3(0., 0., 1.), smoothstep(abs(p.y), abs(p.y), fwidth(p.y) * 2.));
return col;
}

vec2 eval(in vec2 p, in vec2 sp, in vec2 ep, in float d, in float s) {

    vec2 v = ep - sp;
    vec2 a = p - sp;
    // vec2 b = a - v * clamp(dot(a, v) / dot(v, v), 0.0, 1.0);
    vec2 b = a - v * clamp(dot(a, v) / pow(length(v), 2.), 0.0, 1.0);
    d = min(d, dot(b, b));
    bvec3 cond = bvec3(p.y >= sp.y, p.y < ep.y, v.x * a.y > v.y * a.x);

    if(all(cond) || all(not(cond)))
        s = -s;

    return vec2(s, d);
}

float sdPolygon(in vec2 p, in vec2 lt,in vec2 rt,in vec2 lb,in vec2 rb) {

  
    // 当前点到左上角点的 模长平方
    float d = dot(p - lt, p - lt);
    float s = 1.0;
    vec2 res = eval(p, lt, lb, d, s);
    s = res.x;
    d = res.y;
    res = eval(p, rt, lt, d, s);
    s = res.x;
    d = res.y;
    res = eval(p, rb, rt, d, s);
    s = res.x;
    d = res.y;
    res = eval(p, lb, rb, d, s);
    s = res.x;
    d = res.y;
    return s * sqrt(d);
}

vec3 drawPoints(in vec2 p, in vec2[4] v, in vec3 col) {
    for(int i = 0; i < v.length(); i++) {
        vec2 pos = v[i];
        col = drawPoint(p, pos, fwidth(p.y) * 5., vec3(1., 0., 0.), col);
    }
    return col;
}

/*
*绘制线段
*
*/
vec3 drawSegment(in vec2 p, in vec2 sp, in vec2 ep, in float w, in vec3 color, in vec3 col) {

    vec2 v = ep - sp;
    vec2 v1 = sp - ep;
    vec2 a = p - sp;
    vec2 a1 = p - ep;
    //计算夹角
    float theta = dot(v, a) / pow(length(v), 2.);
    float d = length(v) * theta;
    float b = sqrt(pow(length(a), 2.) - pow(d, 2.));
    if(dot(v, a) > 0.0 && dot(v1, a1) > 0.) {
        col = mix(col, color, smoothstep(w, w * 0.99, b));
    }
    return col;
}

void mainImage(out vec4 fragColor,in vec2 fragCoord){
vec2 p = fixuv(fragCoord);
vec3 col  = drawGrid(p);

vec2 lt = vec2(0.,0.);
vec2 rt = vec2(0.,0.);
vec2 rb = vec2(0.,0.);
vec2 lb = vec2(0.,0.);

fragColor =vec4(col,1.);
}


